package com.yifeng.repo.base.utils.codec;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * Created by daibing on 2018/7/9.
 */
public class HmacSHA1 {

    public static String genHMACBase64Encoded(String data, String key) {
        byte[] result = null;
        try {
            //根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
            SecretKeySpec signinKey = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA1");
            //生成一个指定 Mac 算法 的 Mac 对象
            Mac mac = Mac.getInstance("HmacSHA1");
            //用给定密钥初始化 Mac 对象
            mac.init(signinKey);
            //完成 Mac 操作
            byte[] rawHmac = mac.doFinal(data.getBytes("UTF-8"));
            //Base64编码
            result = Base64Helper.encodeBase64(rawHmac);
            return new String(result, "UTF-8");
        } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        String data = "GET\n" +
                "\n" +
                "application/x-protobuf\n" +
                "Fri, 16 Oct 2020 01:52:19 GMT\n" +
                "x-log-apiversion:0.6.0\n" +
                "x-log-bodyrawsize:0\n" +
                "x-log-signaturemethod:hmac-sha1\n" +
                "/logstores/spinus-logx/index?from=1602259200&line=100&offset=0&query=appId=x_fire_mps and 用户&reverse=true&to=1602777599&topic=testing&type=log";
        String key = "**********";
//        String data = "GET&%2F&AccessKeyId%3DHrtDZBqhGv660OU6%26Action%3DOnsInstanceCreate%26Format%3DJSON%26InstanceName%3Dx-link-topicx-dev-brm%26PreventCache%3D1551861059572%26RegionId%3Dcn-shenzhen%26ServiceCode%3Dons%26SignatureMethod%3DHMAC-SHA1%26SignatureNonce%3D39a94a05-4f5e-4e7b-b06a-4da50fea0e3815518610671571%26SignatureVersion%3D1.0%26Timestamp%3D2019-03-06T08%253A31%253A07Z%26Version%3D2019-02-14";
//        String key = "RobdohyxhcWTCp2JYZLVm53yU6eVpI&";
        String result = HmacSHA1.genHMACBase64Encoded(data, key);
        System.out.println("result : " + result);
        //xrcvLfShXIxLaTG8Q20wHGcz4rY=
    }



}
